package cn.tide.question2.controller;

import cn.tide.question2.dao.UserDao;
import cn.tide.question2.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("")
public class UserController {

    @RequestMapping("/Q4Servlet")
    public void login(HttpServletRequest request, HttpServletResponse response){
        String name = request.getParameter("username");
        String password = request.getParameter("password");

//        System.out.println(name+",,,,"+password);
        UserDao userDao = new UserDao();
        User user = userDao.findByNameAndPassword(name, password);

//        System.out.println();

        if(null==user){
            try {
                request.getRequestDispatcher("/q4/fail.jsp").forward(request,response);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        request.getSession().setAttribute("user", user);

        try {
            request.getRequestDispatcher("/q4/success.jsp").forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/Q4Exit")
    public void exit(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("user");
        try {
            request.getRequestDispatcher("/q4/index.jsp").forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
